package com.heima.search.service.Impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.search.dto.AssociateDto;
import com.heima.model.common.search.pojo.ApUserSearch;
import com.heima.model.common.search.vo.AssociateWordsVo;
import com.heima.search.service.HistoryService;
import com.heima.utils.common.UserContext;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RestHighLevelClient  restHighLevelClient;
    @Override
    @Async
    public void saveSearchHistory(ApUserSearch apUserSearch) {
        //查询用户是否保存过关键字
        //保存过 ,更新时间
        // 没有。保存

        Query query = Query.query(Criteria.where("userId").is(apUserSearch.getUserId()).and("keyword").is(apUserSearch.getKeyword()));
        ApUserSearch one = mongoTemplate.findOne(query, ApUserSearch.class);
        if(one!=null){
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
        }else {
            mongoTemplate.save(apUserSearch);
        }
    }

    /**
     * 查询搜索历史的API接口
     * @return
     */
    @Override
    public ResponseResult<List<ApUserSearch>> load() {
        Long userId = UserContext.getUserId();
        List<ApUserSearch> list = new ArrayList<>();
        if (userId!=null) {
            Query query = Query.query(Criteria.where("userId").is(userId));
            query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
            query.with(PageRequest.of(0, 10));
            list = mongoTemplate.find(query, ApUserSearch.class);
            return ResponseResult.okResult(list);
        }
        return ResponseResult.okResult(list);
    }
   // 删除搜索历史
    @Override
    public ResponseResult del(String id) {
        Long userId = UserContext.getUserId();
        ApUserSearch apUserSearch = mongoTemplate.findById(id, ApUserSearch.class);
        if (apUserSearch==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!userId.equals(apUserSearch.getUserId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        Query query = Query.query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult();
    }

    /**
     * 自动补全
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<List<AssociateWordsVo>> searchAssociate(AssociateDto dto) throws IOException {

        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SuggestBuilder suggestBudder =new SuggestBuilder();
        suggestBudder.addSuggestion("suggestResult", SuggestBuilders.
                completionSuggestion("labels").prefix(dto.getSearchWords()
        ).skipDuplicates(true).size(dto.getPageSize()));
        searchRequest.source().suggest(suggestBudder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Suggest suggest = searchResponse.getSuggest();
        List<AssociateWordsVo>  resultList= new ArrayList<>();
        Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestResult = suggest.getSuggestion("suggestResult");
        for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> options : suggestResult) {
            List<? extends Suggest.Suggestion.Entry.Option> list = options.getOptions();
            for (Suggest.Suggestion.Entry.Option option : list) {
                Text text = option.getText();
                resultList.add(new AssociateWordsVo(text.toString()));
            }

        }
        return ResponseResult.okResult(resultList);
    }
}
